package com.xiaoyy.sso.core.integration.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoyy.core.common.cache.CacheConst;
import com.xiaoyy.core.common.enums.BoolEnum;
import com.xiaoyy.core.common.enums.UserTypeEnum;
import com.xiaoyy.core.common.exception.AppException;
import com.xiaoyy.core.config.util.RedisUtil;
import com.xiaoyy.sso.common.vo.UserVO;
import com.xiaoyy.sso.core.dao.model.SysUser;
import com.xiaoyy.sso.core.integration.SmsIntegration;
import com.xiaoyy.sso.core.service.SysUserService;
import com.xiaoyy.sso.core.util.UserSecureUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 发送短信接口
 * */
@Service
public class SmsIntegrationImpl implements SmsIntegration {
    private static Pattern cellphonePattern = Pattern.compile("^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$");//1开头 第二位是3或4或5或7或8 总11位
    @Autowired
    RedisUtil redisUtil;
    @Value("${system.config.login.sms.clock}")
    private Long clockTime;
    @Value("${system.config.login.sms.check.time}")
    private Long checkTime;
    @Value("${system.config.login.sms.max}")
    private Integer smsMax;

    @Autowired
    SysUserService sysUserService;
    @Override
    public void loginSendMsg(String cellphone,String smsSendType,String userType,String orgId) {
        Matcher m = cellphonePattern.matcher(cellphone);
        if (!m.matches()){
            throw new AppException("请输入正确的手机号码");
        }
        if (redisUtil.hasKey(CacheConst.SYS_CLOCK_SHORT_MESSAGE+cellphone)){
            throw new AppException("因发送次数过多，该手机号码发送短信验证码被锁定1小时");
        }
        String key = CacheConst.LOGIN_SHORT_MSG_CODE+cellphone;
        //生成短信验证码
        String shortCode = RandomUtil.randomNumbers(4);
        // 测试手机号码，短信验证码为0000
        if (cellphone.equalsIgnoreCase("15168331001")){
            shortCode = "0000";
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getCellphone, UserSecureUtil.aesEncrypt(cellphone))
                .eq(SysUser::getUserType,userType)
                .eq(SysUser::getDel, BoolEnum.FALSE.getType());
        if (UserTypeEnum.COMPANY.getType().equalsIgnoreCase(userType)){
            if (StringUtils.isBlank(orgId)){
                throw new AppException("请选择需要登录的企业或单位");
            }
            queryWrapper.lambda().eq(SysUser::getOrgId, orgId);
            // todo 验证是否专管员或企业法人身份证

        }
        List<SysUser> sysUsers = sysUserService.list(queryWrapper);
        // 发送短信
        String message="";
        if ("forgetPassword".equalsIgnoreCase(smsSendType)){
            if (CollectionUtils.isEmpty(sysUsers)){
                throw new AppException("该手机号码未注册");
            }
            message="您本次密码重置的短信验证码为：";
        }else if ("register".equalsIgnoreCase(smsSendType)){
            if (!CollectionUtils.isEmpty(sysUsers)){
                throw new AppException("该手机号码已被注册");
            }
            message="您本次注册的短信验证码为：";
        }else if("login".equalsIgnoreCase(smsSendType)){
            if (CollectionUtils.isEmpty(sysUsers)){
                throw new AppException("该手机号码未注册");
            }
            message="您本次登录的短信验证码为：";
        }else if("bindUser".equalsIgnoreCase(smsSendType)){
            message="您本次绑定用户的短信验证码为：";
        }
        message=message+shortCode+"(5分钟内有效)，请务泄露给他人";
        this.sendMessage(cellphone,message);
        int cnt = 1;
        String checkKey=CacheConst.LOGIN_SHORT_MSG_CODE_SEND_CNT+cellphone;
        if (redisUtil.hasKey(checkKey)){
            cnt = cnt+Integer.parseInt(redisUtil.get(checkKey).toString());
            Long time = redisUtil.getExpire(checkKey);
            Date date = new Date(Instant.now().toEpochMilli() + time * 1000);
            redisUtil.set(checkKey,cnt,checkTime);
            redisUtil.expireAt(checkKey,date);
        }else {
            redisUtil.set(checkKey,cnt,checkTime);
        }
        if (cnt>smsMax){
            redisUtil.set(CacheConst.SYS_CLOCK_SHORT_MESSAGE+cellphone,cnt,clockTime);
            throw new AppException("因发送次数过多，该手机号码发送短信验证码被锁定");
        }
        this.sendMessage(cellphone,message);
        redisUtil.set(key,shortCode,300);
    }

    @Override
    public void sendMessage(String cellphone, String message) {

    }

    @Override
    public void sendMessage(List<String> cellphoneList, String message) {

    }

}
